package com.windoent.yugioh.ui.activity.meinfo;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.baidu.mobstat.StatService;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlProgressListener;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;
import com.tencent.cos.xml.transfer.TransferConfig;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.cos.xml.transfer.TransferState;
import com.tencent.cos.xml.transfer.TransferStateListener;
import com.windoent.yugioh.BuildConfig;
import com.windoent.yugioh.R;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.UserInfoBean;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.help.txoss.CosServiceFactory;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.inteface.CitySelectInterface;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.FileUtil;
import com.windoent.yugioh.utils.LogUtils;
import com.windoent.yugioh.utils.StringUtils;
import com.windoent.yugioh.utils.TDevice;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.utils.Utils;
import com.windoent.yugioh.utils.some.utilcode.util.ImageUtils;
import com.windoent.yugioh.widget.ActivityTitle;
import com.windoent.yugioh.widget.HexagonImageView;
import com.windoent.yugioh.widget.UserModifyInfoItem;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.qqtheme.framework.picker.SinglePicker;
import io.reactivex.functions.Consumer;
import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/10 13:20
 * desc   :修改个人信息
 */
public class ModifyUserinfoActivity extends BaseActivity implements View.OnClickListener {
    private ActivityTitle mActivityTitle;
    private ImageView mIvAvatar;
    private LinearLayout mLlModify;
    private UserModifyInfoItem mItemName;
    private UserModifyInfoItem mItemSex;
    private UserModifyInfoItem mItemBirth;
    private UserModifyInfoItem mItemCity;
    private UserModifyInfoItem mItemSignature;
    private Button mBtnSave;
    private CosXmlService cosXmlService;
    private TransferManager transferManager;
    private String bucketRegion = "ap-shanghai";// 存储桶所在地域简称，例如广州地区是 ap-guangzhou
    private COSXMLUploadTask cosxmlTask;
    private String bucket = "yugioh-1258002530"; //存储桶，格式：BucketName-APPID
    private String avatarUrl = "";//头像url
    private String zone_Id = "";
    private String city_Id = "";
    private String county_Id = "";
    private String proviceName = "";
    private String cityName = "";
    private String countryName = "";

    @Override
    public int getLayout() {
        return R.layout.activity_modify_user_info;
    }

    @Override
    public void initView() {
        super.initView();
        mActivityTitle = (ActivityTitle) findViewById(R.id.activity_title);
        immersiveStatusBar(mActivityTitle.getView());
        mIvAvatar = (ImageView) findViewById(R.id.iv_avatar);
        mLlModify = (LinearLayout) findViewById(R.id.ll_modify);
        mItemName = (UserModifyInfoItem) findViewById(R.id.item_name);
        mItemSex = (UserModifyInfoItem) findViewById(R.id.item_sex);
        mItemBirth = (UserModifyInfoItem) findViewById(R.id.item_birth);
        mItemCity = (UserModifyInfoItem) findViewById(R.id.item_city);
        mItemSignature = (UserModifyInfoItem) findViewById(R.id.item_signature);

        mBtnSave = (Button) findViewById(R.id.btn_save);

    }

    @Override
    public void initData() {
        super.initData();
        cosXmlService = CosServiceFactory.getCosXmlService(this, bucketRegion, Constants.COS_SECRET_ID, Constants.COS_SECRET_KEY, true);
        TransferConfig transferConfig = new TransferConfig.Builder().build();
        transferManager = new TransferManager(cosXmlService, transferConfig);
        getUserInfo();
    }

    @Override
    public void initListener() {
        super.initListener();
        mActivityTitle.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mLlModify.setOnClickListener(this);
        mBtnSave.setOnClickListener(this);
        mItemName.setItemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //昵称
                Intent intent = new Intent(ModifyUserinfoActivity.this, ModifyUserNickNameActivity.class);
                intent.putExtra("name", mItemName.getTvContent());
                intent.putExtra("is_name", true);
                startActivityForResult(intent, Constants.MODIFYNICKNAME);
            }
        });
        mItemSignature.setItemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //昵称
                Intent intent = new Intent(ModifyUserinfoActivity.this, ModifyUserNickNameActivity.class);
                intent.putExtra("name", mItemSignature.getTvContent());
                intent.putExtra("is_name", false);
                startActivityForResult(intent, Constants.MODIFYSIGNATURE);
            }
        });
        mItemSex.setItemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //性别
                sexPicker(mItemSex.getTextView());
            }
        });
        mItemBirth.setItemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //选择生日
                String tvContent = mItemBirth.getTvContent();
                if (BaseMethod.notNull(tvContent) && tvContent.contains("-")) {
                    List<String> asList = Arrays.asList(tvContent.split("-"));
                    if (asList.size() == 3) {
                        BaseMethod.showYearMonthDayPicker(ModifyUserinfoActivity.this, mItemBirth.getTextView(), BaseUtils.stringToInt(asList.get(0)), BaseUtils.stringToInt(asList.get(1)), BaseUtils.stringToInt(asList.get(2)));
                    } else {
                        BaseMethod.showYearMonthDayPicker(ModifyUserinfoActivity.this, mItemBirth.getTextView(), 0, 0, 0);
                    }
                } else
                    BaseMethod.showYearMonthDayPicker(ModifyUserinfoActivity.this, mItemBirth.getTextView(), 0, 0, 0);
            }
        });
        mItemCity.setItemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //城市
                BaseMethod.cityPicker(ModifyUserinfoActivity.this, mItemCity.getTextView(), proviceName, cityName, countryName, zone_Id, city_Id, county_Id, new CitySelectInterface() {
                    @Override
                    public void getId(String zoneid, String cityid, String countyid) {
                        zone_Id = zoneid;
                        city_Id = cityid;
                        county_Id = countyid;
                    }
                });
            }
        });


    }


    //六边形头像
    private void setSixAngle(String url, ImageView imageView) {
        Glide.with(ModifyUserinfoActivity.this).asBitmap().load(url).placeholder(R.drawable.drawable_default_avatar).error(R.drawable.drawable_default_avatar).listener(new RequestListener<Bitmap>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.drawable_default_avatar);
                HexagonImageView hexagonImageView = new HexagonImageView(bitmap, imageView.getWidth(), imageView.getHeight());
                imageView.setBackground(hexagonImageView);
                return false;
            }

            @Override
            public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                return false;
            }
        }).into(new CustomTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                Bitmap bitmap = resource == null ? BitmapFactory.decodeResource(getResources(), R.drawable.drawable_default_avatar) : resource;
                HexagonImageView hexagonImageView = new HexagonImageView(bitmap, imageView.getWidth(), imageView.getHeight());
                imageView.setBackground(hexagonImageView);
            }

            @Override
            public void onLoadCleared(@Nullable Drawable placeholder) {
            }
        });

    }

    private void sexPicker(final TextView textView) {
        List<String> data = new ArrayList<>();
        data.add(getString(R.string.sring_man));
        data.add(getString(R.string.string_woman));
        SinglePicker<String> picker = new SinglePicker<>(this, data);
        picker.setCanceledOnTouchOutside(false);
        picker.setSelectedIndex(0);
        picker.setCycleDisable(true);
        picker.setOnItemPickListener(new SinglePicker.OnItemPickListener<String>() {
            @Override
            public void onItemPicked(int index, String item) {
                textView.setText(item);
            }
        });
        picker.show();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.ll_modify:
                //选择照片
                showCameraPhoto();
                break;
            case R.id.camera:
                //点击了从相机选择
                permissionSelecCamera();
                break;
            case R.id.pic:
                permissionSelecPic();
                break;
            case R.id.cancel:
                dialog.dismiss();
                break;
            case R.id.btn_save:
                //保存
                saveUserInfo();
                break;
            default:
                break;
        }
    }


    //头像-----------
    private void showCameraPhoto() {
        dialog = new Dialog(this, R.style.DialogTheme);
        //填充对话框的布局
        View inflate = LayoutInflater.from(this).inflate(R.layout.show_camera_photo, null);
        //初始化控件
        TextView camera = (TextView) inflate.findViewById(R.id.camera);
        TextView pic = (TextView) inflate.findViewById(R.id.pic);
        TextView cancel = (TextView) inflate.findViewById(R.id.cancel);
        camera.setOnClickListener(this);
        pic.setOnClickListener(this);
        cancel.setOnClickListener(this);
        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
        lp.width = (int) (TDevice.getScreenWidth() * 0.9);
        //将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialogWindow.setWindowAnimations(R.style.dialogBottomUpAnimation);//添加动画
        dialog.show();//显示对话框
    }

    private Dialog dialog;
    private Uri origUri;
    private Uri cropUri;
    private String theLarge;
    private final static String FILE_SAVEPATH = Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + "/YingDie/Portrait/";
    private final static int CROP = 400;
    private File protraitFile;
    private Bitmap protraitBitmap;
    private String protraitPath;

    //点击了从相机选择
    private void permissionSelecCamera() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.setLogging(BuildConfig.LOG_DEBUG);
        rxPermissions.request(Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_CALENDAR)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        LogUtils.d("aBoolean:" + aBoolean);
                        if (aBoolean) {
                            dialog.dismiss();
                            startTakePhoto();
                        } else {
                            ToastUtils.showText(getString(R.string.string_no_permission));
                        }
                    }
                });
    }

    //点击了从相册选择
    private void permissionSelecPic() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.setLogging(BuildConfig.LOG_DEBUG);
        rxPermissions.request(Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_CALENDAR)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        LogUtils.d("aBoolean:" + aBoolean);
                        if (aBoolean) {
                            dialog.dismiss();
                            startImagePick();
                        } else {
                            ToastUtils.showText(getString(R.string.string_no_permission));
                        }
                    }
                });
    }

    private void startTakePhoto() {
        Intent intent;
        // 判断是否挂载了SD卡
        String savePath = "";
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            savePath = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/yingdie/Camera/";
            File savedir = new File(savePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        }

        // 没有挂载SD卡，无法保存文件
        if (StringUtils.isEmpty(savePath)) {
            ToastUtils.showText(getString(R.string.string_sd_card_not_save));
            return;
        }

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());
        String fileName = "yingdie_" + timeStamp + ".jpg";// 照片命名
        File out = new File(savePath, fileName);
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            String authority = Utils.getApp().getPackageName() + ".provider";
            uri = FileProvider.getUriForFile(getApplicationContext(), authority, out);
        } else {
            uri = Uri.fromFile(out);
        }
//        Uri uri = Uri.fromFile(out);
        origUri = uri;

        theLarge = savePath + fileName;// 该照片的绝对路径


        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        List<ResolveInfo> resInfoList = getPackageManager()
                .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent,
                Constants.REQUEST_CODE_GETIMAGE_BYCAMERA);
    }

    /**
     * 拍照后裁剪
     *
     * @param data 原始图片
     */
    private void startActionCrop(Uri data) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.putExtra("output", this.getUploadTempFile(data));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", CROP);// 输出图片大小
        intent.putExtra("outputY", CROP);
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        startActivityForResult(intent,
                Constants.REQUEST_CODE_GETIMAGE_BYSDCARD);
    }

    // 裁剪头像的绝对路径
    private Uri getUploadTempFile(Uri uri) {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(FILE_SAVEPATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
            ToastUtils.showText(getString(R.string.string_sd_card_is_mount));
            return null;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());
        String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);

        // 如果是标准Uri
        if (StringUtils.isEmpty(thePath)) {
            thePath = ImageUtils.getRealFilePath(this, uri);
        }
        String ext = FileUtil.getFileFormat(thePath);
        ext = StringUtils.isEmpty(ext) ? "jpg" : ext;
        // 照片命名
        String cropFileName = "yingdie_crop_" + timeStamp + ".png";
        // 裁剪头像的绝对路径
        protraitPath = FILE_SAVEPATH + cropFileName;
        protraitFile = new File(protraitPath);

        cropUri = Uri.fromFile(protraitFile);
        return this.cropUri;
    }

    /**
     * 选择图片裁剪
     */
    private void startImagePick() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, getString(R.string.string_select_picture)),
                    Constants.REQUEST_CODE_GETIMAGE_BYCROP);
        } else {
            intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, getString(R.string.string_select_picture)),
                    Constants.REQUEST_CODE_GETIMAGE_BYCROP);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK)
            return;
        switch (requestCode) {
            case Constants.REQUEST_CODE_GETIMAGE_BYCAMERA:
                startActionCrop(origUri);// 拍照后裁剪
                break;
            case Constants.REQUEST_CODE_GETIMAGE_BYCROP:
                if (data != null)
                    startActionCrop(data.getData());// 选图后裁剪
                break;
            case Constants.REQUEST_CODE_GETIMAGE_BYSDCARD:
                uploadNewPhoto();
                break;
            case Constants.MODIFYNICKNAME:
                //昵称
                if (data != null) {
                    String nick_name = data.getStringExtra("nick_name");
                    mItemName.setConText(nick_name);
                }
                break;
            case Constants.MODIFYSIGNATURE:
                //个性签名
                if (data != null) {
                    String nick_name = data.getStringExtra("nick_name");
                    mItemSignature.setConText(nick_name);
                }
                break;
        }
    }

    //上传
    private void uploadNewPhoto() {
        if (BaseMethod.notNull(protraitPath) && protraitFile.exists()) {
            try {
                upload(protraitPath);
            } catch (Exception e) {
                ToastUtils.showText(e.getMessage());
                e.printStackTrace();
            }
        } else {
            ToastUtils.showText(getString(R.string.string_image_not_exist));
        }
   /*     // 获取头像缩略图
        if (!StringUtils.isEmpty(protraitPath) && protraitFile.exists()) {
            protraitBitmap = ImageUtils
                    .loadImgThumbnail(protraitPath, 200, 200);
            LogUtils.d("imagesize:" + BaseMethod.getBitmapsize(protraitBitmap) / 1024 + "KB," + ",protraitFile" + protraitFile);
        } else {
            ToastUtils.showText(getString(R.string.string_image_not_exist));
        }
        if (protraitBitmap != null) {
            try {
                upload(protraitPath);
            } catch (Exception e) {
                ToastUtils.showText(getString(R.string.string_image_not_exist));
            }
        }*/
    }

    private void upload(String currentUploadPath) {
        if (TextUtils.isEmpty(currentUploadPath)) {
            ToastUtils.showText(getString(R.string.string_please_select_file));
            return;
        }
        if (cosxmlTask == null) {
            File file = new File(currentUploadPath);
            final String cosPath = "Android" + File.separator + System.currentTimeMillis() + file.getName();
            String uploadId = null;
            // 上传文件
            cosxmlTask = transferManager.upload(bucket, cosPath,
                    currentUploadPath, uploadId);
            //设置上传进度回调
            cosxmlTask.setCosXmlProgressListener(new CosXmlProgressListener() {
                @Override
                public void onProgress(final long complete, final long target) {
                    // todo Do something to update progress...
                    LogUtils.d("txoss-->onProgress");
                    uiAction(new Runnable() {
                        @Override
                        public void run() {
                            showLoadingDialog(getString(R.string.string_oss_uploading) + BaseMethod.readableStorageSize(complete) + "/" + BaseMethod.readableStorageSize(target));
                        }
                    });
                }
            });
            //设置返回结果回调
            cosxmlTask.setCosXmlResultListener(new CosXmlResultListener() {
                @Override
                public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                    COSXMLUploadTask.COSXMLUploadTaskResult cOSXMLUploadTaskResult =
                            (COSXMLUploadTask.COSXMLUploadTaskResult) result;
                    hideLoadingDialog();
                    cosxmlTask = null;
                    avatarUrl = result.accessUrl;
                    LogUtils.d("txoss-->" + avatarUrl);
                    uiAction(new Runnable() {
                        @Override
                        public void run() {
                            setSixAngle(avatarUrl, mIvAvatar);
                        }
                    });
                }

                @Override
                public void onFail(CosXmlRequest request,
                                   CosXmlClientException clientException,
                                   CosXmlServiceException serviceException) {
                    hideLoadingDialog();
                    if (cosxmlTask.getTaskState() != TransferState.PAUSED) {
                        cosxmlTask = null;
                    }
                    if (clientException != null) {
                        clientException.printStackTrace();
                    } else {
                        serviceException.printStackTrace();
                    }
                }
            });
            //设置任务状态回调, 可以查看任务过程
            cosxmlTask.setTransferStateListener(new TransferStateListener() {
                @Override
                public void onStateChanged(TransferState state) {
                    // todo notify transfer state
                }
            });
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
        if (cosXmlService != null) {
            cosXmlService.release();
        }
    }

    private void getUserInfo() {
        showLoadingDialog("");
        PhoneLive.getUserInfoByToken(getUserToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            UserInfoBean bean = gson.fromJson(response, UserInfoBean.class);
                            UserInfoBean.DataBean data = bean.getData();
                            if (data != null) {
                                UserInfoBean.DataBean.UserBean user = data.getUser();
                                if (user != null) {
                                    setTextUI(user);
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });

    }

    //设置数据
    private void setTextUI(UserInfoBean.DataBean.UserBean data) {
        avatarUrl = data.getAvatar();
        setSixAngle(avatarUrl, mIvAvatar);
        mItemName.setConText(BaseMethod.notNullDefaultValueNull(data.getNickName()));
        mItemSex.setConText(BaseMethod.notNullDefaultValue(data.getGender(), getString(R.string.string_interval)));
        mItemBirth.setConText(BaseMethod.notNullDefaultValue(data.getBirthday(), getString(R.string.string_interval)));
        mItemCity.setConText(BaseMethod.notNullDefaultValue(data.getAreaString(), getString(R.string.string_interval)));
        mItemSignature.setConText(BaseMethod.notNullDefaultValueNull(data.getSignature()));
        zone_Id = data.getZoneId() + "";
        city_Id = data.getCityId() + "";
        county_Id = data.getCountyId() + "";
        proviceName = data.getZone();
        cityName = data.getCity();
        countryName = data.getCounty();
    }

    //保存
    private void saveUserInfo() {
        String name = mItemName.getTvContent();
        String sex = mItemSex.getTvContent();
        String birthday = mItemBirth.getTvContent();
        String city = mItemCity.getTvContent();
        String signature = mItemSignature.getTvContent();
        boolean notEmpty = notEmpty(name, sex, birthday, city);
        if (notEmpty) {
            showLoadingDialog("");
            PhoneLive.saveUserInfo(getUserToken(), name, sex, birthday, zone_Id, city_Id, county_Id, signature, BaseMethod.getUrlImageSubString(avatarUrl), new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    hideLoadingDialog();
                    ToastUtils.showText(e.getMessage());
                }

                @Override
                public void onResponse(String response, int id) {
                    hideLoadingDialog();
                    if (BaseUtils.isJSONValid(response)) {
                        try {
                            if (BaseUtils.codeIs0(mContext, response)) {
                                finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        ToastUtils.showText(getString(R.string.string_response_error));
                    }
                }
            });
        }

    }

    //判空
    private boolean notEmpty(String name, String sex, String birthday, String city) {
        if (BaseMethod.isNull(name) || name.equals(getString(R.string.string_interval))) {
            ToastUtils.showText(getString(R.string.string_name_null));
            return false;
        } else if (BaseMethod.isNull(sex) || sex.equals(getString(R.string.string_interval))) {
            ToastUtils.showText(getString(R.string.string_gender_null));
            return false;
        } else if (BaseMethod.isNull(birthday) || birthday.equals(getString(R.string.string_interval))) {
            ToastUtils.showText(getString(R.string.string_birthday_null));
            return false;
        } else if (BaseMethod.isNull(city) || city.equals(getString(R.string.string_interval))) {
            ToastUtils.showText(getString(R.string.string_city_null));
            return false;
        } else return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "修改个人信息界面");
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "修改个人信息界面");
    }
}
